package mcu;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

public class McuService {

	public static void main(String[] args) {

		String msgHexValue = "40 01 00 00 00 00 00 00";
		String signalBitRange = "7-1";

		show(msgHexValue, signalBitRange);
	}

	private static void show(String msgHexValue, String signalBitRange) {

		System.out.println("消息值16进制: " + msgHexValue);
		System.out.println("信号占位情况: " + signalBitRange);

		// 16进制转2进制
		String msgBinaryValue = hexToBinary(msgHexValue);
		System.out.println("消息值2进制: " + msgBinaryValue);

		// 真实的小端排序 index
		List<String> littleEndianIndexes = initLittleEndianIndexes();
		System.out.println("真实的小端排序index: " + littleEndianIndexes);

		// 解析出真实的信号值
		int realSignalValue = resolveSignalValue(signalBitRange, littleEndianIndexes, msgBinaryValue);
		System.out.println("信号真实值: " + realSignalValue);
	}

	private static List<String> initLittleEndianIndexes() {
		List<String> indexes = new ArrayList<>();
		for (int index = 0; index <= 7; index++) {
			for (int y = 1; y <= 8; y++) {
				indexes.add(String.valueOf((index + 1) * 8 - y));
			}
		}
		return indexes;
	}

	private static String hexToBinary(String hexString) {
		hexString = hexString.replace(" ", "");
		StringBuilder binaryString = new StringBuilder();

		for (int i = 0; i < hexString.length(); i += 2) {
			String hexByte = hexString.substring(i, i + 2);
			int decimal = Integer.parseInt(hexByte, 16);
			binaryString.append(String.format("%8s", Integer.toBinaryString(decimal)).replace(' ', '0'));
			binaryString.append(" ");
		}
		return binaryString.toString();
	}

	private static int resolveSignalValue(String signalBitRange, List<String> littleEndianIndexes,
			String msgBinaryValue) {
		msgBinaryValue = msgBinaryValue.replace(" ", "");

		String[] parts = signalBitRange.split("-");
		int startBit = Integer.parseInt(parts[0]);
		int endBit = Integer.parseInt(parts[1]);

		StringBuilder realSignalBinaryText = new StringBuilder();

		for (int index = startBit; index >= endBit; index--) {
			realSignalBinaryText.append(msgBinaryValue.charAt(littleEndianIndexes.indexOf(String.valueOf(index))));
		}

		return new BigInteger(realSignalBinaryText.toString(), 2).intValue();
	}
}
